﻿using System;
using System.Collections.Generic;
using System.Text;
using log4net.Appender;
using log4net.Core;
using log4net.Layout;

namespace WHO_Auth_TNG_Win {
    public class LogViewHandler : log4net.Appender.AppenderSkeleton {

        private System.Windows.Forms.ListBox myList;
        private LinkedList<String> queuedEvents = new LinkedList<string>();

        public LogViewHandler(System.Windows.Forms.ListBox myList) {
            this.myList = myList;
            this.Layout = new log4net.Layout.PatternLayout("%d{HH:mm:ss}    %message");
            this.Threshold = log4net.Core.Level.Info;
        }

        override protected bool RequiresLayout {
            get { return false; }
        }

        override protected void Append(log4net.Core.LoggingEvent loggingEvent) {
            if (myList.IsHandleCreated) {                
                myList.BeginInvoke(new ListAddDelegate(addEventToList), RenderLoggingEvent(loggingEvent));
            } else {
                queuedEvents.AddLast(RenderLoggingEvent(loggingEvent));
            }     
        }

        public void showRememberedEvents(Object sender, EventArgs ev) {
            foreach (string e in queuedEvents) {
                myList.BeginInvoke(new ListAddDelegate(addEventToList), e);
            }
            queuedEvents.Clear();
        }

        private void addEventToList(String eventToAdd) {
            myList.Items.Insert(0, eventToAdd);
            while (myList.Items.Count > 50) {
                myList.Items.RemoveAt(49);
            }
        }

        delegate void ListAddDelegate(String e);

        
    }
}
